package com.gamebase.net.rpc
{
	import flash.utils.ByteArray;
	import flash.utils.Endian;
	
	public class SocketHeader
	{
		public static const CSheaderLength:uint = 12;
		public static const SCheaderLength:uint = 10;
		public var flag:uint;//2:s-c 还是3:c-s的返回
		
		public var length:uint;
		public var iid:uint;//服务器ID
		public var sid:uint;//服务器上的不同 类对象ID
		public var validate:uint;//校验码
		public var err_code:int;//错误码
		public var serializer:Serializer; //包
		public var buffer:ByteArray;
		private var bytes:ByteArray;
		
		public function SocketHeader()
		{
			length = 0;
			flag = 3;
			validate = 0;
			iid = 0;
			sid = 1;
			bytes = new ByteArray();
			bytes.endian = Endian.BIG_ENDIAN;
			buffer = new ByteArray();
			buffer.endian = Endian.BIG_ENDIAN;
			serializer = new Serializer(buffer);
			
		}
		
		public function reset():void
		{
			buffer.clear();
			bytes.clear()
			length = 0;
			serializer.hasError = false;
		}
		
		public function decodeLength():void
		{
			length = buffer.readUnsignedInt();
		}
		
		public function encodeLength():void
		{
			length = buffer.length;
			serializer.writeUnsignedInt(length);
		}
		
		
		public function encode($data:Object=null):void
		{
			
			if($data != null)
			{
				serializer.encodeData($data, bytes);
				length = bytes.length;
			}
			else
				length = 0;
			buffer.position = 0;
			serializer.writeUnsignedInt(length+CSheaderLength);
			
			serializer.writeShort(iid);
			serializer.writeShort(sid);
			serializer.writeUnsignedInt(validate);
			if($data != null)
				serializer.writeByteArray(bytes);
			
		}
		
		public function decodeHead():void
		{
			
			length = serializer.readUnsignedInt();
			iid = serializer.readUnsignedShort();
			sid = serializer.readUnsignedShort();
			err_code = serializer.readUnsignedShort();
		}
		
		public function cloneSerializer():Serializer
		{
			var ba:ByteArray = new ByteArray();
			ba.endian = Endian.BIG_ENDIAN;
			ba.writeBytes(buffer, 0, buffer.bytesAvailable);
			ba.position = 0;
			var s:Serializer = new Serializer(ba);
			return s;
		}
		
	}
}